package com.service.information.imp;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import org.springframework.core.io.FileSystemResource;  
import com.po.MailBean;
import java.util.Iterator; 
import com.service.information.MailSenderService;

@Service
public class MailSenderServiceImp implements MailSenderService {
	@Autowired
	private JavaMailSenderImpl javaMailSenderImpl;

	@Override
	public MimeMessage createMimeMessage(MailBean mailBean) throws MessagingException, UnsupportedEncodingException {
		
		MimeMessage mimeMessage = javaMailSenderImpl.createMimeMessage();
		MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
		messageHelper.setFrom(javaMailSenderImpl.getUsername(), mailBean.getFromName());
		messageHelper.setSubject(mailBean.getSubject());
		messageHelper.setTo(mailBean.getToEmails());
		messageHelper.setText(mailBean.getContext(), true); // html: true

		// 添加附件
		if (null != mailBean.getAttachments()) {
			for (Iterator<Map.Entry<String, String>> it = mailBean.getAttachments().entrySet().iterator(); it.hasNext();) {
				Map.Entry<String, String> entry = it.next();
				String cid = entry.getKey();
				String filePath = entry.getValue();
				if (null == cid || null == filePath) {
					throw new RuntimeException("请确认每个附件的ID和地址是否齐全！");
				}
				File file = new File(filePath);
				if (!file.exists()) {
					throw new RuntimeException("附件" + filePath + "不存在！");
				}
				FileSystemResource fileResource = new FileSystemResource(file);
				messageHelper.addAttachment(cid, fileResource);
			}
		}
		return mimeMessage;
	}

	@Override
	public void sendMail(MailBean mailBean) throws UnsupportedEncodingException, MessagingException {
		MimeMessage msg = createMimeMessage(mailBean);
		javaMailSenderImpl.send(msg);
	}

}
